<?php

namespace Icsoc\ReportBundle\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Icsoc\ExportLib\Col;

/**
 * Class DataController
 * @package Icsoc\ReportBundle\Controller
 */
class DataController extends ReportController
{
    private $callType = array('1'=>'呼出', '2'=>'呼入'); //呼叫类型
    /**
     * 技能组来电分配报表
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function inallotAction()
    {
        $isSpecial = $this->container->get("icsoc_core.common.class")->getIsAdmin();
        $options = array(
            'result'=>array('text'=>'Call In Result', 'type'=>2, 'options'=>$this->container->getParameter('CALLINRESULT'))
        );
        return $this->render('IcsocReportBundle:Data:inallotDataList.html.twig', array(
            'options' => $options,
            'date' => $this->getData(),
            'isSpecial' => $isSpecial
        ));
    }

    /**
     * 技能组来电分配数据
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function inallotListAction(Request $request)
    {
        $data = $request->get('param', '');
        $data = html_entity_decode(urldecode($data));

        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'id');
        $export = $request->get('export', '');

        $info = array(
            'pagination' => array('rows'=>$rows, 'page'=>$page),
            'filter' => !empty($data) ? json_decode($data, true) : array(),
            'sort' => array('order'=>$sord, 'field'=>$sidx),
        );

        $list = $this->get('icsoc_data.model.report')->getInallotListData(
            array(
                'vcc_code'=>$this->getVccCode(),
                'info'=>json_encode($info)
            )
        );

        /** 导出功能 */
        if (!empty($export)) {

            /** @var  $title (导出字段) */
            $title = array(
                'que_name' =>'Queue',
                'num' =>'Allot Num',
                'rate' =>'Proportion'
            );

            $translator = $this->get('translator');
            switch ($export) {
                case 'csv':
                    return $this->exportCsv($list['data'], json_encode($title), array(
                        'text' => $translator->trans('Queue Inallot Report'),
                        'href' => $this->generateUrl('icsoc_report_inallot')
                    ));
                case 'excel':
                    return $this->exportExcel($list['data'], json_encode($title), array(
                        'text' => $translator->trans('Queue Inallot Report'),
                        'href' => $this->generateUrl('icsoc_report_inallot')
                    ));
                default:
                    exit;
            }
        }

        $result = array(
            'records' => isset($list['total']) ? $list['total'] : 0,
            'rows' => $list['data'],
            'code' => isset($list['code']) ? $list['code'] : '',
            'message' => isset($list['message']) ? $list['message'] : '',
        );

        return new JsonResponse($result);
    }

    /**
     * 满意度评价汇总表
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function evaluateCollecAction()
    {
        $vccId = $this->getVccId();
        $data = $this->container->get('icsoc_data.model.evaluate')->getEvaluateVerByVccId($vccId);
        $isSpecial = $this->container->get("icsoc_core.common.class")->getIsAdmin();  
        /** 获取所有坐席 **/
        $agName = $this->get('icsoc_data.model.agent')->getAgentNameKeyedByIdArray($vccId, true);
        if ($data == 1) {
            $em = $this->getDoctrine()->getManager();
            $isEnableGroup = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")->isEnableGroup($vccId);
            /*获取所有业务组*/
            $groups = $em->getRepository("IcsocSecurityBundle:WinGroup")->getGroupsName($vccId);
            /** @var  $queues (全部技能组数据) */
            $queues = $this->get('icsoc_data.model.queue')->getQueueNameKeyedByIdArray($this->getUser()->getVccId(), true);
            /** @var array $evaluates 满意度评价结果 */
            $evaluates = $this->container->getParameter('EVALUATES');
            $options = array(
                'ag_id'=>array('text'=>'Username', 'type'=>2, 'options'=>$agName),
                'que_id'=>array('text'=>'Queue', 'type'=>2, 'options'=>$queues),
                'call_type'=>array('text'=>'Call type', 'type'=>2, 'options'=>$this->callType),
            );
            if ($isEnableGroup) {
                $options['group_id'] = array('text'=>'Business Group', 'type'=>2, 'options'=>$groups);
            }

            return $this->render('IcsocReportBundle:Data:evaluateCollecList2.html.twig', array(
                'options' => $options,
                'title' => $evaluates,
                'date' => $this->getData(),
                'isEnableGroup'=>$isEnableGroup,
                'isSpecial' => $isSpecial
            ));
        }
        /** @var array $evaluates 满意度评价结果 */
        $evaluates = $this->container->get('icsoc_data.model.evaluate')->getEvaluateConfig(array('vccId' => $vccId));
        $otherData = json_decode($evaluates, true);
        $evaluateConfig = array();
        $groupData = array();
        if (!empty($otherData)) {
            $num = 0;
            $k = 1;
            foreach ($otherData as $key => $val) {
                if (!empty($val['keys']) && is_array($val['keys'])) {
                    $firstNum = 1;
                    $firstIndex = '';
                    foreach ($val['keys'] as $kval) {
                        if ($firstNum == 1) {
                            $firstIndex = $kval['id'];
                        }
                        $evaluateConfig[$num++] = array('index'=>$kval['id'], 'name'=>$kval['name']);
                        $startNum = $num;
                        $evaluateConfig[$num++] = array('index'=>$kval['id'].'_rate', 'name'=>trim($kval['name']).'率');
                        if (isset($kval['child']['keys']) && !empty($kval['child']['keys'])) {
                            foreach ($kval['child']['keys'] as $ckval) {
                                $evaluateConfig[$num++] = array('index'=>$ckval['id'], 'name'=>$ckval['name']);
                                $evaluateConfig[$num++] = array('index'=>$ckval['id'].'_rate', 'name'=>trim($ckval['name']).'率');
                            }
                            $groupData[] = array('start_name'=>$firstIndex, 'number'=>$firstNum*2, 'text'=>'满意度评价'.$k);
                            $groupData[] = array(
                                'start_name'=>$evaluateConfig[$startNum+1]['index'],
                                'number'=>count($kval['child']['keys']) * 2,
                                'text'=>$kval['name'].'-二级满意度'
                            );
                            $firstNum = 1;
                        } else {
                            $firstNum++;
                        }
                    }
                    $groupData[] = array('start_name'=>$firstIndex, 'number'=>($firstNum-1)*2, 'text'=>'满意度评价'.$k);
                }
                $k++;
            }
        }
        $options = array(
            'ag_id'=>array('text'=>'Username', 'type'=>2, 'options'=>$agName),
        );

        return $this->render(
            'IcsocReportBundle:Data:evaluateCollecList.html.twig',
            array(
                'options' => $options,
                'title' => $evaluateConfig,
                'group_data'  => $groupData,
                'date' => $this->getData()['day'],
                'isSpecial' => $isSpecial,
            )
        );
    }

    /**
     * 满意度评价汇总列表数据
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function evaluateCollecListAction(Request $request)
    {
        $data = $request->get('param', '');
        $data = html_entity_decode(urldecode($data));

        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'desc');
        $sidx = $request->get('sidx', 'ag_id');
        $export = $request->get('export', '');

        $info = array(
            'pagination' => array('rows'=>$rows, 'page'=>$page),
            'filter' => !empty($data) ? json_decode($data, true) : array(),
            'sort' => array('order'=>$sord, 'field'=>$sidx),
        );

        $list = $this->get('icsoc_data.model.report')->getEvaluateCollectListDataFromElasticsearch(
            array(
                'vcc_code'=>$this->getVccCode(),
                'info'=>json_encode($info),
            )
        );

        /** 导出功能 */
        if (!empty($export)) {
            /** @var  $title (导出字段) */
            $title = array(
                'ag_num' =>'坐席工号',
                'ag_name' => '坐席姓名',
                'evalute1' => '成功评价次数',
                'defeat' => '未成功评价次数',
                'evalute-1' => '客户挂机',
                'evalute-3' => '未评价挂机',
                'evalute-4' => '坐席挂机',
                'transfer_rate' => '转接率',
                'evalute_rate' => '参评率',
            );
            $evaluates = $this->container->get('icsoc_data.model.evaluate')->getEvaluateConfig(array('vccId' => $this->getVccId()));
            $otherData = json_decode($evaluates, true);
            if (!empty($otherData)) {
                foreach ($otherData as $key => $val) {
                    if (!empty($val['keys']) && is_array($val['keys'])) {
                        foreach ($val['keys'] as $kval) {
                            $title[$kval['id']] = $kval['name'];
                            $title[$kval['id'].'_rate'] = trim($kval['name']).'率';
                            if (isset($kval['child']['keys']) && !empty($kval['child']['keys'])) {
                                foreach ($kval['child']['keys'] as $ckval) {
                                    $title[$ckval['id']] = $ckval['name'];
                                    $title[$ckval['id'].'_rate'] = trim($ckval['name']).'率';
                                }
                            }
                        }
                    }
                }
            }
            $list['data'][] = $list['footer'];
            $translator = $this->get('translator');
            switch ($export) {
                case 'csv':
                    return $this->exportCsv($list['data'], json_encode($title), array(
                        'text' => $translator->trans('Evaluate Collect Report'),
                        'href' => $this->generateUrl('icsoc_report_evaluatecollec'),
                    ));
                case 'excel':
                    return $this->exportExcel($list['data'], json_encode($title), array(
                        'text' => $translator->trans('Evaluate Collect Report'),
                        'href' => $this->generateUrl('icsoc_report_evaluatecollec'),
                    ));
                default:
                    exit;
            }
        }
        $result = array(
            'total' => isset($list['total_pages']) ? $list['total_pages'] : 0,
            'page' => isset($list['page']) ? $list['page'] : 1,
            'records' => isset($list['total']) ? $list['total'] : 0,
            'rows' => $list['data'],
            'userdata' => $list['footer'],
            'code' => isset($list['code']) ? $list['code'] : '',
            'message' => isset($list['message']) ? $list['message'] : '',
        );

        return new JsonResponse($result);
    }

    /**
     * 老的满意度评价汇总列表数据
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function evaluateCollecList2Action(Request $request)
    {
        $data = $request->get('param', '');
        $data = html_entity_decode(urldecode($data));

        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'desc');
        $sidx = $request->get('sidx', 'ag_id');
        $export = $request->get('export', '');

        $info = array(
            'pagination' => array('rows'=>$rows, 'page'=>$page),
            'filter' => !empty($data) ? json_decode($data, true) : array(),
            'sort' => array('order'=>$sord, 'field'=>$sidx),
        );

        $list = $this->get('icsoc_data.model.report')->getEvaluateCollectListData(
            array(
                'vcc_code'=>$this->getVccCode(),
                'info'=>json_encode($info),
            )
        );

        $gridData = array();

        $translator = $this->get('translator');

        $footer['ag_num'] = $translator->trans('Total');
        $footer['success'] = 0;
        $footer['defeat'] = 0;
        $evaluate = array_keys($this->container->getParameter('EVALUATES'));
        foreach ($evaluate as $val) {
            $footer[sprintf('e%s', $val)] = 0;
        }

        if (isset($list['code']) && $list['code'] == 200) {
            foreach ($list['data'] as $k => $v) {
                $gridData[$k] = $v;
                //$gridData[$k]['ag_num'] = $v['ag_num']." ".$v['ag_name'];
                $footer['success'] += $v['success']; //成功评价
                $footer['defeat'] += $v['defeat']; //未成功评价
                foreach ($evaluate as $val) {
                    $footer[sprintf('e%s', $val)] += $v[sprintf('e%s', $val)];
                }
            }
        }

        /** 导出功能 */
        if (!empty($export)) {
            /** @var  $title (导出字段) */
            $title = array(
                'ag_num' =>'Agent Num',
                'ag_name' => 'Agent Name',
                'success' =>'Success Num',
                'defeat' =>'Defeat Num',
            );

            /** @var  $evaluates 满意度评价结果 */
            $evaluates = $this->container->getParameter('EVALUATES');
            foreach ($evaluates as $k => $v) {
                $title['e'.$k] = ' '.$v;
            }

            $gridData[] = $footer;

            switch ($export) {
                case 'csv':
                    return $this->exportCsv($gridData, json_encode($title), array(
                        'text' => $translator->trans('Evaluate Collect Report'),
                        'href' => $this->generateUrl('icsoc_report_evaluatecollec'),
                    ));
                case 'excel':
                    return $this->exportExcel($gridData, json_encode($title), array(
                        'text' => $translator->trans('Evaluate Collect Report'),
                        'href' => $this->generateUrl('icsoc_report_evaluatecollec'),
                    ));
                default:
                    exit;
            }
        }

        $result = array(
            'total' => isset($list['total_pages']) ? $list['total_pages'] : 0,
            'page' => isset($list['page']) ? $list['page'] : 1,
            'records' => isset($list['total']) ? $list['total'] : 0,
            'rows' => $gridData,
            'userdata' => $footer,
            'code' => isset($list['code']) ? $list['code'] : '',
            'message' => isset($list['message']) ? $list['message'] : '',
        );

        return new JsonResponse($result);
    }

    /**
     * 坐席签到数据报表
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function agentSignInAction()
    {
        $vccId = $this->getVccId();
        $isSpecial = $this->container->get("icsoc_core.common.class")->getIsAdmin();
        //查询所有坐席
        $agName = $this->get('icsoc_data.model.agent')->getAgentNameKeyedByIdArray($vccId, true);

        return $this->render(
            'IcsocReportBundle:Data:agentSignIn.html.twig',
            array(
                'ag_name' => $agName,
                'date' =>  $this->getData(),
                'isSpecial' => $isSpecial,
            )
        );
    }

    /**
     * 坐席签到数据报表列表
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function agentSignInListAction(Request $request)
    {
        $data = $request->get('data', '');
        $data = html_entity_decode(urldecode($data));
        $data = json_decode($data, true);
        $item = array();
        $item['start_date'] = empty($data['start_date']) ? '' : $data['start_date'];
        $item['end_date'] = empty($data['end_date']) ? '' : $data['end_date'];
        $item['ag_id'] = empty($data['ag_id']) ? 'all' : $data['ag_id'];
        $item['caption'] = '坐席签到数据报表 【  %start_date% ~ %end_date%】';
        $title = $this->get('icsoc_report_for_role.model.report')->proccessStaReason(array(), 'day');
        foreach ($title as $key => $val) {
            if (strstr($key, 'agstaduration')) {
                $title[$key]['text'] = $val['text'].' (h)';
            }
        }

        return $this->render('IcsocReportBundle:Data:agentSignInList.html.twig', array(
            'item'=>$item,
            'title' => $title,
        ));
    }

    /**
     * 坐席签到数据报表数据
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function agentSignInDataAction(Request $request)
    {
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'id');
        $param = $request->get('param', '');
        $info = array(
            'filter'=> json_decode($param),
            'sort'=>array('order' => $sord, 'field' => $sidx),
        );
        $export = $request->get('export', '');
        $vccId = $this->getVccId();
        $list = $this->get('icsoc_data.model.report')->getAgentWorkData(array('vcc_id'=>$vccId, 'info'=>json_encode($info)));
        $gridData = array();
        if (isset($list['code']) && $list['code'] == 200) {
            $gridData = $list['data'];
        }
        /** 导出功能 */
        if (!empty($export)  && $list['code'] == 200) {
            $item = $this->get('icsoc_report_for_role.model.report')->proccessStaReason(array(), 'day');
            /** @var  $title (导出字段) */
            $title = array(
                'ag_num' => array(
                    'title' => 'Agent number',
                    'type' => Col::TYPE_STRING,
                ),
                'ag_name' => array(
                    'title' => 'Username',
                    'type' => Col::TYPE_STRING,
                ),
                'sum' => array(
                    'title' => '工作天数(天)',
                    'type' => Col::TYPE_STRING,
                ),
                'login_hour' => array(
                    'title' => '登录时长(h)',
                    'type' => Col::TYPE_STRING,
                ),
                'ready_hour' => array(
                    'title' => '空闲时长(h)',
                    'type' => Col::TYPE_STRING,
                ),
                'busy_hour' => array(
                    'title' => '总示忙时长(h)',
                    'type' => Col::TYPE_STRING,
                ),
            );
            if (isset($item) && !empty($item) && is_array($item)) {
                foreach ($item as $key => $val) {
                    if (strstr($key, 'agstaduration')) {
                        $title[$val['field']] =array(
                            'title' => $val['text'].' (h)',
                            'type' => Col::TYPE_STRING,
                        );
                    } else {
                        $title[$val['field']] =array(
                            'title' => $val['text'],
                            'type' => Col::TYPE_STRING,
                        );
                    }
                }
            }
            $gridData[] = $list['footer'];
            switch ($export) {
                case 'csv':
                    return $this->container->get('icsoc_data.model.batchExport')->exportCsv($title, $gridData);
                case 'excel':
                    return $this->container->get('icsoc_data.model.batchExport')->exportExcel($title, $gridData);
                default:
                    exit;
            }
        }

        $result = array(
            'records' => isset($list['total']) ? $list['total'] : 0,
            'rows' => $gridData,
            'userdata' => isset($list['footer']) ? $list['footer'] : '',
            'code' => isset($list['code']) ? $list['code'] : '',
            'message' => isset($list['message']) ? $list['message'] : '',
        );

        return new JsonResponse($result);
    }

    /**
     * 通话重复号码统计报表
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function repetitionPhoneAction()
    {
        $isSpecial = $this->container->get("icsoc_core.common.class")->getIsAdmin();

        return $this->render('IcsocReportBundle:Data:callRepetitionPhoneAction.html.twig', array(
            'date' => $this->getData()['day'],
            'isSpecial' => $isSpecial,
        ));
    }

    /**
     * 通话重复号码统计报表数据
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|JsonResponse
     */
    public function repetitionPhoneDataAction(Request $request)
    {
        $param = $request->get('param', '');
        $export = $request->get('export', '');
        $info = array(
            'filter'=> json_decode($param),
            'sort'=>array('rows' => empty($export) ? 1000 : 10000),
        );
        $vccId = $this->getVccId();
        $list = $this->get('icsoc_data.model.report')->getMgRepetitionPhoneData(array('vcc_id'=>$vccId, 'info'=>json_encode($info)));
        $gridData = array();
        if (isset($list['code']) && $list['code'] == 200) {
            $gridData = $list['data'];
        }
        /** 导出功能 */
        if (!empty($export)  && $list['code'] == 200) {
            /** @var  $title (导出字段) */
            $title = array(
                'phone' => array(
                    'title' => '号码',
                    'type' => Col::TYPE_STRING,
                ),
                'call_type' => array(
                    'title' => '通话类型',
                    'type' => Col::TYPE_STRING,
                ),
                'dial_num' => array(
                    'title' => '拨号数量',
                    'type' => Col::TYPE_STRING,
                ),
                'connect' => array(
                    'title' => '接通数量',
                    'type' => Col::TYPE_STRING,
                ),
                'no_connect' => array(
                    'title' => '未接通数量',
                    'type' => Col::TYPE_STRING,
                ),
                'connect_rate' => array(
                    'title' => '接通比例',
                    'type' => Col::TYPE_STRING,
                ),
            );
            switch ($export) {
                case 'csv':
                    return $this->container->get('icsoc_data.model.batchExport')->exportCsv($title, $gridData);
                case 'excel':
                    return $this->container->get('icsoc_data.model.batchExport')->exportExcel($title, $gridData);
                default:
                    exit;
            }
        }

        $result = array(
            'rows' => $gridData,
            'code' => isset($list['code']) ? $list['code'] : '',
            'message' => isset($list['message']) ? $list['message'] : '',
        );

        return new JsonResponse($result);
    }
}
